﻿using Base.Infrastructure.Dto.Request.GetQuestions;
using Base.Infrastructure.Dto.Request.option;
using Base.Infrastructure.Dto.Request.UserExam;
using Base.Infrastructure.Dto.Response;
using Base.Infrastructure.EFCore.MySql;
using Base.Infrastructure.IOC;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Base.Service.Instance
{
    public class UserExamService : BaseService, Base.Service.Interface.IUserExamService
    {
        private readonly UserExamIOC _userExamIOC;
        private readonly ArrangeIOC _arrangeIOC;
        private readonly TestPaperDetailIOC _testPaperDetailIOC;
        private readonly QuestionIOC _questionIOC;
        private readonly optionIOC _optionIOC;
        private readonly TestPaperIOC _testPaperIOC;

        public UserExamService(UserExamIOC userExamIOC, ArrangeIOC arrangeIOC , TestPaperDetailIOC testPaperDetailIOC, QuestionIOC questionIOC, optionIOC optionIOC, TestPaperIOC  testPaperIOC, IConfiguration configuration)
        {
            _userExamIOC = userExamIOC;
            _arrangeIOC = arrangeIOC;
            _testPaperDetailIOC = testPaperDetailIOC;
            _questionIOC = questionIOC;
            _optionIOC = optionIOC;
            _testPaperIOC = testPaperIOC;
        }

        /// <summary>
        /// （开始考试）根据考试id获取题目
        /// </summary>
        /// <param name="UEUID"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult GetExamQuestions(string UEID)
        {
            //查询考试表中的安排id
            var ai = _userExamIOC._userExamService.QueryAll(d => d.Ueid == UEID && d.Uestate !=1 && d.Uestate!=2);
            if (ai.Any())
            {
                var ia = ai.Single();

                //改变考试状态/添加考生开始时间
                ia.UestartTime= DateTime.Now.ToString();
                ia.Uestate = 0;
                _userExamIOC._userExamService.Update(ia);
                _userExamIOC._userExamService.SaveChanges();

                //查询安排表中的试卷id
                var ai2 = _arrangeIOC._arrangeService.QueryAll(d => d.Aid == ia.Ueaid);
                if (ai2.Any())
                {
                    var ia2 = ai2.Single();

                    if (DateTime.Parse(ia2.AbeginTime) > DateTime.Now)
                    {
                        return GetResult(-1, "当前考试还未开始");
                    }

                    //查询试卷详情中的题目id和分数
                    var ai3 = _testPaperDetailIOC._testPaperDetailService.QueryAll(d => d.Tpdtpid == ia2.AtpId);
                    if (ai3.Any())
                    {
                        //获取试卷所有的题目和分数
                        var list = ai3.Select(d => new
                        {
                            TPDQID=d.Tpdqid,
                            TPDScore=d.Tpdscore
                        }).ToList();

                        //获取考试剩余时间
                        var AEndTime = ia2.AendTime;//获取考试结束时间
                        var TimeRemaining =DateTime.Parse(AEndTime) - DateTime.Now;//减去当前时间得到剩余时间
                        

                       //用于返回的集合
                        var list_options = new List<GetQuestionsRequestDto>();

                        //获取题目所有选项
                        foreach (var item in list) {
                            var questions = _questionIOC._questionService.QueryAll(d => d.Qid == item.TPDQID).Single();
                            var options = _optionIOC._optionService.QueryAll(d => d.Oqid == item.TPDQID).ToList();
                            
                            //将题目选项分数剩余时间添加到集合
                            list_options.Add(new GetQuestionsRequestDto
                            {
                                Qid= questions.Qid,
                                Qcontent=questions.Qcontent,
                                Qtype= questions.Qtype,
                                Ocontent = options,
                                TPDScore=item.TPDScore,
                                TimeRemaining=TimeRemaining.ToString()
                            });
                        }

                        return GetResult(1, data: list_options);
                    }
                    else
                    {
                        return GetResult(-1, "没有此试卷");
                    }
                }
                else
                {
                    return GetResult(-1, "没有此安排");
                }
            }
            else
            {
                return GetResult(-1, "该考试已结束");
            }
        }

        /// <summary>
        /// 获取个人已结束的考试
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult Querytest(string UEUID)
        {

            //获取用户所有结束的考试
            var arrange_id = new List<SelExamArrangeRequestDto>();
            var ai = _userExamIOC._userExamService.QueryAll(d => d.Ueuid == UEUID&&d.Uestate>=1);
            if (ai.Any())
            {
           
                var ia = ai.Select(d => new
                {
                    Ueid = d.Ueid,
                    Ueuid=d.Ueuid,
                    Ueaid=d.Ueaid,
                    Uecode =d.Uecode,
                    UestartTime=d.UestartTime,
                    UefinishTime=d.UefinishTime,
                    UeisCheck=d.UeisCheck,
                    UecheckUid=d.UecheckUid,
                    Uescore=d.Uescore,
                    UecreateTime=d.UecreateTime,
                    Uestate=d.Uestate
                }).ToList();
                foreach (var it in ia)
                {
                    var aiI = _userExamIOC._userExamService.QueryAll(d => d.Ueuid == it.Ueid && d.Uestate >=1).ToList();
                    var aname = _arrangeIOC._arrangeService.QueryAll(d => d.Aid == it.Ueaid).Single();
                    arrange_id.Add(new SelExamArrangeRequestDto
                    {
                        Aname = aname.Aname,
                        AbeginTime = aname.AbeginTime,
                        AendTime = aname.AendTime,
                        Ueid = it.Ueid,
                        Ueuid = it.Ueuid,
                        Ueaid = it.Ueaid,
                        Uecode = it.Uecode,
                        UestartTime = it.UestartTime,
                        UefinishTime = it.UefinishTime,
                        UeisCheck = it.UeisCheck,
                        UecheckUid = it.UecheckUid,
                        Uescore = it.Uescore,
                        UecreateTime = it.UecreateTime,
                        Uestate = it.Uestate
                    }); ;
                }
                return GetResult(1, data: arrange_id);
            }
            else
            {
                return GetResult(-1, "该用户暂无有关考试信息");
            }
        }

        /// <summary>
        /// （交卷）
        /// </summary>
        /// <param name="UEID"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult Submit(OcontentRequestDto dto)
        {
            //查询考试表
            var ai = _userExamIOC._userExamService.QueryAll(d => d.Ueid == dto.UEID).Single();

            var list_Ocontent = new List<OcontentRequestDto>();

            float? Score = 0;
            //拿到传回来的选项id进行验证是否正确
            for (var i=0;i<dto.OID?.Length;i++)
            {
                var Test0 = _optionIOC._optionService.QueryAll(d => d.Oid == dto.OID[i]);
                
                if (!Test0.Any())
                {
                    continue;
                }
                var Test = Test0.Single();
               //获取回答正确的题目id
                if (Test.OisRight==1)
                {
                    //获取回答正确的题目分数
                    var TestPaper = _testPaperDetailIOC._testPaperDetailService.QueryAll(d => d.Tpdqid == Test.Oqid).Single();

                    Score =Score +TestPaper.Tpdscore;
                }
            }

            ai.UefinishTime = DateTime.Now.ToString();
            ai.UeisCheck = 1;
            ai.UecheckUid = "系统阅卷";
            ai.Uescore = Score;
            ai.Uestate = 1;
            _userExamIOC._userExamService.Update(ai);
            _userExamIOC._userExamService.SaveChanges();

            return GetResult(1,"交卷完成",data: Score);
        }

        /// <summary>
        /// 获取未完成的考试
        /// </summary>
        /// <param name="UEUID"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult Unfinishedexams(string UEUID)
        {
            //获取可以考试的安排id
            var currenttime = _userExamIOC._userExamService.QueryAll(d=>d.Ueuid== UEUID && d.Uestate != 1 && d.Uestate != 2);
            var time = currenttime.Select(d => new
            {
                UEAID=d.Ueaid
            }).ToList();

            //遍历所有安排id获取所有考试结束时间
            var list_arrange = new List<Arrange>();
            foreach (var item in time)
            {
                var selArrange = _arrangeIOC._arrangeService.QueryAll(d => d.Aid == item.UEAID).Single();
                list_arrange.Add(new Arrange
                {
                    Aid= selArrange.Aid,
                    AendTime = selArrange.AendTime
                });
            }

            //遍历所有时间查询已超时结束的考试 
            var datetemi = DateTime.Now;
            var list_UserExam = new List<SelUserExamRequestDto>();
            foreach (var item2 in list_arrange)
            {
                if (datetemi>DateTime.Parse(item2.AendTime))
                {
                    list_UserExam.Add(new SelUserExamRequestDto
                    {
                        UEAID = item2.Aid
                    });
                }
            }

            //把该用户所有超时结束的考试更改状态
            //如果该用户已参与考试则自动交卷，如果没有参与考试则为缺考
            foreach (var UserExam in list_UserExam)
            {
                var UpUserExam0 = _userExamIOC._userExamService.QueryAll(d => d.Ueaid == UserExam.UEAID && d.Ueuid== UEUID);
                if (UpUserExam0.Any())
                {
                    var UpUserExam = UpUserExam0.Single();
                   
                        UpUserExam.UefinishTime = datetemi.ToString();
                        UpUserExam.UeisCheck = 1;
                        UpUserExam.UecheckUid = "系统阅卷";
                        UpUserExam.Uescore = 0;
                        UpUserExam.Uestate = 2;
                        _userExamIOC._userExamService.Update(UpUserExam);
                        _userExamIOC._userExamService.SaveChanges();
                  
                }
                }


            var arrange_id = new List<SelExamArrangeRequestDto>();
            //最后返回该用户暂未完成的考试
            var ai = _userExamIOC._userExamService.QueryAll(d => d.Ueuid == UEUID && d.Uestate != 1 && d.Uestate != 2);
            if (ai.Any())
            {

                var ia = ai.Select(d => new
                {
                   
                    Ueid = d.Ueid,
                    Ueuid = d.Ueuid,
                    Ueaid = d.Ueaid,
                    Uecode = d.Uecode,
                    UestartTime = d.UestartTime,
                    UefinishTime = d.UefinishTime,
                    UeisCheck = d.UeisCheck,
                    UecheckUid = d.UecheckUid,
                    Uescore = d.Uescore,
                    UecreateTime = d.UecreateTime,
                    Uestate = d.Uestate
                }).ToList();


                foreach (var it in ia)
                {
                    var aiI = _userExamIOC._userExamService.QueryAll(d => d.Ueuid == it.Ueid && d.Uestate != 1 && d.Uestate != 2).ToList();
                    var aname = _arrangeIOC._arrangeService.QueryAll(d => d.Aid == it.Ueaid).Single();
                    arrange_id.Add(new SelExamArrangeRequestDto
                    {
                        Aname = aname.Aname,
                        AbeginTime=aname.AbeginTime,
                        AendTime=aname.AendTime,
                        Ueid = it.Ueid,
                        Ueuid = it.Ueuid,
                        Ueaid = it.Ueaid,
                        Uecode = it.Uecode,
                        UestartTime = it.UestartTime,
                        UefinishTime = it.UefinishTime,
                        UeisCheck = it.UeisCheck,
                        UecheckUid = it.UecheckUid,
                        Uescore = it.Uescore,
                        UecreateTime = it.UecreateTime,
                        Uestate = it.Uestate
                    }); ;
                }
                return GetResult(1, data: arrange_id);
            }
            else
            {
                return GetResult(1, "该用户暂无未完成的考试信息");
            }
        }
    }
}
